package com.me.mysqladmin.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.me.mysqladmin.entity.SQLCommand;
import com.me.mysqladmin.service.SQLService;
import com.me.mysqladmin.util.EasyUIFormat;

@Controller
@RequestMapping("/sqlCommand")
public class SQLCommandController extends BaseController {
	// 注入业务组件
	@Resource
	private SQLService sqlService;
	
	/**
	 * 打开主页
	 */
	@RequestMapping("/index.do")
	public String toIndex(){
		return "main/SQLCommand";
	}
	
	/**
	 * 执行SQL语句
	 * @param sqlCommand
	 * @return
	 */
	@RequestMapping("/execute.do")
	@ResponseBody
	public Map<String, Object> execute(SQLCommand sqlCommand){
		try {
			LOG.info("--------执行SQL：" + sqlCommand.getSql() + "--------");
			sqlCommand = sqlService.executeSql(sqlCommand.getSql());
			if(sqlCommand.getType() == "query"){
				return EasyUIFormat.parseGrid(sqlCommand.getRs(), LinkedHashMap.class);
			} else{
				return messageSuccess(sqlCommand.getLines());
			}
		} catch (Exception e) {
			return messageFailure(e.getMessage(), "执行SQL失败！");
		}
	}
}
